package com.example.service;

import com.example.entity.Balance;
import com.example.entity.BalanceToken;
import com.example.mapper.BalanceMapper;
import com.example.mapper.BalanceTokenMapper;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

@Service
public class BalanceService {

    @Resource
    private BalanceMapper balanceMapper;

    @Resource
    private BalanceTokenMapper balanceTokenMapper;

    /**
     * 同步ETH余额，按钱包地址幂等写入
     */
    public void syncEthBalance(String address, BigDecimal ethBalance) {
        if (address == null || ethBalance == null) return;
        Balance exist = balanceMapper.selectOne(
                new QueryWrapper<Balance>()
                .eq("wallet_address", address)
        );
        if (exist == null) {
            Balance b = new Balance();
            b.setWalletAddress(address);
            b.setEthBalance(ethBalance);
                b.setUpdateTime(new Date());
            balanceMapper.insert(b);
        } else {
            exist.setEthBalance(ethBalance);
                exist.setUpdateTime(new Date());
            balanceMapper.updateById(exist);
        }
    }

    /**
     * 同步Token余额，按钱包地址+合约地址幂等写入
     */
    public void syncTokenBalance(String address, String tokenAddress, BigDecimal tokenBalance) {
        if (address == null || tokenAddress == null || tokenBalance == null) return;
        BalanceToken exist = balanceTokenMapper.selectOne(
                new QueryWrapper<BalanceToken>()
                .eq("wallet_address", address)
                .eq("token_address", tokenAddress)
        );
        if (exist == null) {
            BalanceToken t = new BalanceToken();
            t.setWalletAddress(address);
            t.setTokenAddress(tokenAddress);
            t.setTokenBalance(tokenBalance);
                t.setUpdateTime(new Date());
            balanceTokenMapper.insert(t);
        } else {
            exist.setTokenBalance(tokenBalance);
                exist.setUpdateTime(new Date());
            balanceTokenMapper.updateById(exist);
        }
    }

}
